<?php 
namespace App\Service;

use App\Lib\Curl;

use Exception;
use log;

class SteamService extends BaseService
{

	public static $URL = 'http://api.steampowered.com/ISteamEconomy/GetAssetClassInfo/v0001?';
	public static $TRADEHISTORY = 'https://api.steampowered.com/IEconService/GetTradeHistory/v1?';
	public static $TRADEOFFER = 'https://api.steampowered.com/IEconService/GetTradeOffer/v1?';
	public static $TRADEOFFERS = 'https://api.steampowered.com/IEconService/GetTradeOffers/v1?';
	public static $CANCELTRADEOFFER = 'https://api.steampowered.com/IEconService/CancelTradeOffer/v1?';
	public static $TRADESTATUS= 'https://api.steampowered.com/IEconService/GetTradeStatus/v1?';
	public static $INVENTORY = 'https://steamcommunity.com/inventory/%s/%s/2/?';

	public static $instance = null;

	public static function getInstance()
	{
		if (self::$instance == null) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	/**
	 * 获取steam报价列表
	 * @param  string $apiKey
	 * @return array
	 */
	public function getOffers($apiKey)
	{
		//https://api.steampowered.com/IEconService/GetTradeOffers/v1/?key=9DFE1BA9F158478C4E789F9E2CCCB172&get_sent_offers=1&get_received_offers=1
		try{
			$params = array(
				'key' => $apiKey,
				'get_sent_offers' => 1,
				'active_only' => 1,
				'format' => 'json',
			);
			$url = self::$TRADEOFFERS.http_build_query($params);
			$result = Curl::http_get($url);
			$result = json_decode($result ,true);
			if (!empty($result['response'])) {
				return $result['response'];
			}
			return false;
		} catch (Exception $e) {
			echo $e->getMessage();
			return false;
		}
	}

	/**
	 * 取消steam报价
	 * @param  string $apiKey
	 * @return array
	 */
	public function cancelTradeById($key, $tradeofferId)
	{
		try{
			$params = array(
				'key' => $key,
				'tradeofferid' => $tradeofferId,
				'format' => 'json',
			);
			$url = self::$CANCELTRADEOFFER.http_build_query($params);
			$result = Curl::http_post(self::$CANCELTRADEOFFER, $params);
			$result = json_decode($result ,true);
			if(isset($result['response'])){
				return true;
			}
			return false;
		} catch (Exception $e) {
			echo $e->getMessage();
			return false;
		}
	}

	/**
	 * 获取单个报价信息
	 * @param  string $apiKey
	 * @param  string $tradeofferId
	 * @param  string $time 次数
	 * @return array
	 */
	public function getTradeoffer($key, $tradeofferId, $time = 0)
	{
		try{
			$params = array(
				'key' => $key,
				'tradeofferid' => $tradeofferId,
				'format' => 'json',
			);
			$url = self::$TRADEOFFER.http_build_query($params);
			$result = Curl::http_get($url);
			if (empty($result)) {
				return false;
			}
			$result = json_decode($result ,true);
			if (!empty($result['response']['offer'])) {
				return $result['response']['offer'];
			} elseif ($time<2) {
				$time += 1;
				return $this->getTradeoffer($key, $tradeofferId, $time);
			} else {
				return false;
			}
		} catch (Exception $e) {
			echo $e->getMessage();
			return false;
		}
	}

	/**
	 * 获取报价历史信息
	 * @param  string $apiKey
	 * @param  string $tradeofferId
	 * @param  string $time 次数
	 * @return array
	 */
	public function getTradeOfferHistory($key, $limit = 500)
	{
		try{
			$params = array(
				'key' => $key,
				'max_trades' => $limit,
				'format' => 'json',
				'include_failed' => 1
			);
			$url = self::$TRADEHISTORY.http_build_query($params);
			$result = Curl::http_get($url);
			if(empty($result)){
				return false;
			}
			$result = json_decode($result ,true);
			if (!empty($result['response']['trades'])) {
				return $result['response']['trades'];
			}
			return false;
		}catch (Exception $e){
			echo $e->getMessage();
			return false;
		}
	}

	/**
	 * 获取报价状态
	 * @param  string $key
	 * @param  string $tradeId
	 * @return array|bool
	 */
    public function getTradeStatus($key, $tradeId, $received = true)
    {
		try{
			$params = array(
					'key'=>$key,
					'format'=>'json',
					'tradeid'=>$tradeId,
			);
			$url = self::$TRADESTATUS.http_build_query($params);
			$items = [];
			echo $url;
			$result = Curl::http_get($url);
			if(empty($result)){
				return false;
			}
			$result = json_decode($result ,true );
			
			if(!empty($result['response']['trades'][0])){
				if($received === true){
					foreach ($result['response']['trades'][0]['assets_received'] as $item){
						$items[] =(Object)[
							'o_id'=>	$item['assetid'],
							'id'=>	$item['new_assetid'],
							'appid'=>	$item['appid'],
							'contextid'=>$item['contextid'],
							'classid'=>	$item['classid'],
							'instanceid'=>	$item['instanceid'],
							'amount'=>$item['amount']
						];
					}
				}elseif($received === false){
					foreach ($result['response']['trades'][0]['assets_given'] as $item){
						$items[] =(Object)[
							'o_id'=>	$item['assetid'],
							'id'=>	$item['new_assetid'],
							'appid'=>	$item['appid'],
							'contextid'=>$item['contextid'],
							'classid'=>	$item['classid'],
							'instanceid'=>	$item['instanceid'],
							'amount'=>$item['amount']
						];
					}
				}
				return $items;
			}
			return false;
        } catch (Exception $e) {
            echo $e->getMessage();
            return false;
        }
    }

	/**
	 * 获取库存
	 * @param  string $steamId 
	 * @param  int $appId 游戏类型
	 * @return array
	 */
	public function getInvsList($steamId, $appId)
	{
		try{
			$params = array(
				'trading' => 1,
				'count' => 5000
			);
			$url = sprintf(self::$INVENTORY, $steamId, $appId).http_build_query($params);
			$result = Curl::http_get($url, 'zh-cn');
			if (empty($result)) {
				return false;
			}

			$result = json_decode($result, true);
			return $result;
		} catch (Exception $e) {
			echo $e->getMessage();
			return false;
		}
	}
}